package com.diuse.lib.util.helper;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Json帮助类
 * Created by Administrator on 2015/10/25 0025.
 */
public class JsonHelp {

    private static Logger logger = Logger.getLogger(JsonHelp.class);
    private static Gson sGson = new Gson();

    public static String jsonFromObject(Object object) {
        return sGson.toJson(object);
    }

    public static <T> T objectFromJson(String json, Class<T> clz) {
        T object =  null;
        try {
            object = sGson.fromJson(json, clz);
        } catch (JsonSyntaxException e) {
            logger.error("Json Cast error, from " + json + " to " + clz.toString(),  e.getCause());
        }
        return object;
    }

    public static<T> T objectFromJson(InputStream in, Class<T> clz) {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            T object = sGson.fromJson(reader, clz);
            reader.close();
            return object;
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e.getCause());
        } catch (IOException e) {
            logger.error(e.getMessage(), e.getCause());
        }

        return null;
    }



    public static<T> List<T> praseListFromJson(String jsonString, Class<T> clz) {
        List<T> result = new ArrayList<T>();
        Class mapClass = null;
        try {
            mapClass = Class.forName("java.util.HashMap");
            Map map =  (Map) JsonHelp.objectFromJson(jsonString, mapClass);
            String msgStr = (String) map.get("msg");
            //sGson = new Gson();
            result= sGson.fromJson(msgStr, new TypeToken<List<T>>() {
            }.getType());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }





    public static void main(String args[]) {
//        String jsonStr = "{\"result\":true,\"msg\":[{\"sid\":8837,\"userId\":3,\"longitude\":122.16421,\"latitude\":29.997753,\"content\":\"噢噢噢哦哦陌陌\",\"imgUrl1\":\"diuse-studio.oss-cn-shanghai.aliyuncs.com/20151120230230.jpg\",\"haveResponse\":false,\"readed\":false,\"publishTime\":1448031751248,\"expireTime\":1449031751248,\"typeId\":0}]}";
//        praseTaskDataStructFromJson(jsonStr);
    }
}
